package com.buddy.learn.elasticsearch.task;

import com.buddy.learn.elasticsearch.entity.TestData;
import com.buddy.learn.elasticsearch.repository.TestDataRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Buddy
 * @date 2021/4/25
 */
//@Component
public class TaskTestData implements ApplicationRunner {

    private static final Logger LOG = LoggerFactory.getLogger(TaskTestData.class);

    @Autowired
    private TestDataRepository testDataRepository;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                20, 50,
                1, TimeUnit.HOURS,
                new LinkedBlockingQueue<>(),
                Thread::new,
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        for (int i = 10000; i <= 31000; i++) {
            int finalI = i;
            poolExecutor.execute(() -> {
                long startTime1 = System.currentTimeMillis();
                List<TestData> list = new ArrayList<>(65000);
                for (int j = 0; j <= 65000; j++) {
                    LOG.info("batchNum={},current={}", finalI, j);
                    list.add(new TestData(j + (finalI * 65000), j, j & 255, (j / 10.0f)));
                }
                testDataRepository.saveAll(list);
                long endTime = System.currentTimeMillis();
                LOG.info("batchNum={},timeUse={}ms", finalI, (endTime - startTime1));
            });
        }
    }
}
